package com.anysoft.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Form表格构造器
 *
 * @since 1.6.13.26 [20201114 duanyy] <br>
 */
public class FormBuilder {
    /**
     * 编码
     */
    public static final String ENCODING_UTF8 = "utf-8";

    /**
     * logger of slf4j
     */
    public static final Logger LOG = LoggerFactory.getLogger(UrlBuilder.class);

    /**
     * 参数
     */
    protected List<Pair<String,String>> params = new ArrayList<Pair<String,String>>();

    public FormBuilder(){

    }

    public FormBuilder addParameters(String name,String value){
        params.add(new Pair.Default<String,String>(name,value));
        return this;
    }

    public String build(){
        return build(ENCODING_UTF8);
    }

    public String build(String encoding){
        StringBuffer buffer = new StringBuffer();
        boolean first = true;
        for (Pair<String,String> p:params){
            String id = p.key();
            String value = p.value();
            if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(value)){
                try {
                    if (!first){
                        buffer.append("&");
                    }
                    String encoded = URLEncoder.encode(value, encoding);
                    buffer.append(id).append("=").append(encoded);
                    first = false;
                } catch (UnsupportedEncodingException e) {
                    LOG.error(String.format("Encoding %s is not supported", encoding));
                }
            }
        }
        return buffer.toString();
    }
}

